<script lang="ts" setup name="warehouseModelDetail">
import { reactive, onMounted } from "vue";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';
import { useWarePlaceModelApi, type WarePlaceModel, type PageWarePlaceModelInput } from '/@/api/interacting/warehouse/warePlaceModel';
import { getDepartmentList, getUserList } from '/@/api/customer/userList';
import { useSysLogOpApi, type SysLogOp, type PageSysLogOpInput } from '/@/api/system/sysLogOp';

const route = useRoute();
const router = useRouter();
const warehouseModelApi = useWarehouseModelApi();
const warePlaceModelApi = useWarePlaceModelApi();
const sysLogOpApi = useSysLogOpApi();

const state = reactive({
  loading: false,
  warehouseData: {} as any, // 仓库详细信息
  departmentList: [] as any[], // 部门列表
  userList: [] as any[], // 用户列表
  activeTab: 'locationInfo', // 当前激活的标签页
  // 库位信息查询参数
  locationQueryParams: {} as any,
  locationSelectData: [] as any[], // 选中的库位数据
  locationTableParams: {
    page: 1,
    pageSize: 10,
    total: 10,
  },
  locationTableData: [] as any[], // 库位数据（显示用）
  allLocationData: [] as any[], // 所有库位数据（原始数据，用于查询过滤）
  locationTableLoading: false,
  locationFormLoading: false,
  // 操作记录相关状态
  operationLogQueryParams: {} as any,
  operationLogTableParams: {
    page: 1,
    pageSize: 10,
    total: 0,
  },
  operationLogTableData: [] as SysLogOp[], // 操作记录数据
  operationLogTableLoading: false,
});

// 加载基础数据
const loadBaseData = async () => {
  // 加载部门列表
  try {
    const res = await getDepartmentList();
    state.departmentList = Array.isArray(res) ? res : [];
  } catch (error) {
    console.error('加载部门列表失败:', error);
  }

  // 加载用户列表
  try {
    const res = await getUserList();
    let userList = res?.data?.result || res?.result || [];
    if (userList.length === 0) {
      userList = res?.data || res || [];
    }
    state.userList = userList.map((item: any) => ({
      ...item,
      value: String(item.value),
      label: item.label
    }));
  } catch (error) {
    console.error('加载用户列表失败:', error);
  }
};

// 根据部门ID获取部门名称
const getDepartmentName = (departmentId: any) => {
  if (!departmentId) return '';
  const department = state.departmentList.find(item => item.value == departmentId);
  return department ? department.label : departmentId;
};

// 根据用户ID获取用户名称
const getUserName = (userId: any) => {
  if (!userId) return '';
  const user = state.userList.find(item => item.value == userId);
  return user ? user.label : userId;
};

// 加载仓库详情
const loadWarehouseDetail = async () => {
  const warehouseId = route.params.id || route.query.id;
  if (!warehouseId) {
    ElMessage.error('仓库ID不存在');
    router.back();
    return;
  }

  state.loading = true;
  try {
    const res = await warehouseModelApi.detail(warehouseId);
    state.warehouseData = res.data.result || {};
    console.log('仓库详情数据:', state.warehouseData);
  } catch (error) {
    console.error('加载仓库详情失败:', error);
    ElMessage.error('加载仓库详情失败');
  } finally {
    state.loading = false;
  }
};

// 返回列表页
const goBack = () => {
  router.back();
};

// 加载库位数据
const loadWarePlaceData = async () => {
  state.locationTableLoading = true;
  try {
    // 检查仓库是否有分配的库位
    const warehouseWarePlaceIds = state.warehouseData.warePlaceId;
    console.log('仓库分配的库位ID:', warehouseWarePlaceIds);
    
    if (!warehouseWarePlaceIds) {
      // 如果没有分配库位，显示空数据和提示
      state.allLocationData = [];
      state.locationTableData = [];
      state.locationTableParams.total = 0;
      console.log('该仓库未分配任何库位');
      return;
    }

    // 解析库位ID（支持逗号分隔的多个库位）
    const warePlaceIds = typeof warehouseWarePlaceIds === 'string' 
      ? warehouseWarePlaceIds.split(',').map(id => id.trim()).filter(id => id)
      : Array.isArray(warehouseWarePlaceIds) 
      ? warehouseWarePlaceIds 
      : [warehouseWarePlaceIds];

    console.log('解析后的库位ID列表:', warePlaceIds);

    // 加载所有库位数据
    const params: PageWarePlaceModelInput = {
      page: 1,
      pageSize: 1000,
      keyword: '',
    };

    const res = await warePlaceModelApi.page(params);
    const allWarePlaces = res.data?.result.items || [];
    console.log('所有库位数据:', allWarePlaces);

    // 过滤出该仓库分配的库位
    const assignedWarePlaces = allWarePlaces.filter((item: WarePlaceModel) => 
      warePlaceIds.some(id => 
        String(item.id) === String(id) || 
        item.id === id ||
        item.id == id
      )
    );

    console.log('过滤后的库位数据:', assignedWarePlaces);

    // 转换数据格式，适配原有的显示逻辑
    state.allLocationData = assignedWarePlaces.map((item: WarePlaceModel) => ({
      ...item,
      locationCode: item.warePlaceCode,
      locationName: item.warePlaceName,
      locationVolume: item.warePlaceVolume,
      locationManager: getUserName(item.userId),
      locationStatus: item.warePlaceType,
      locationNote: item.warePlaceNote,
    }));

    state.locationTableData = [...state.allLocationData];
    state.locationTableParams.total = state.allLocationData.length;

    console.log('库位数据加载成功:', state.allLocationData);
  } catch (error) {
    console.error('加载库位数据失败:', error);
    ElMessage.error('加载库位数据失败');
  } finally {
    state.locationTableLoading = false;
  }
};

// 查询库位
const handleLocationQuery = () => {
  const { locationCode, locationStatus, locationManager } = state.locationQueryParams;

  // 从所有数据中过滤
  let filteredData = [...state.allLocationData];

  // 按仓位名称/编号过滤
  if (locationCode) {
    filteredData = filteredData.filter(item =>
      item.locationCode.includes(locationCode) ||
      item.locationName.includes(locationCode)
    );
  }

  // 按状态过滤
  if (locationStatus !== '' && locationStatus !== undefined) {
    const status = locationStatus === '1' || locationStatus === 1;
    filteredData = filteredData.filter(item => item.locationStatus === status);
  }

  // 按库位主管过滤
  if (locationManager) {
    filteredData = filteredData.filter(item =>
      item.locationManager.includes(locationManager)
    );
  }

  state.locationTableData = filteredData;
  state.locationTableParams.total = filteredData.length;
  state.locationTableParams.page = 1; // 重置到第一页
};

// 重置查询
const handleLocationReset = () => {
  state.locationQueryParams = {};
  state.locationTableData = [...state.allLocationData];
  state.locationTableParams.total = state.allLocationData.length;
  state.locationTableParams.page = 1;
};


// 删除库位
const handleDeleteLocation = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个库位吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    await warePlaceModelApi.delete({ id: row.id });
    ElMessage.success('删除库位成功');

    // 重新加载数据
    await loadWarePlaceData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除库位失败:', error);
      ElMessage.error('删除库位失败');
    }
  }
};

// 加载操作记录数据
const loadOperationLogData = async () => {
  state.operationLogTableLoading = true;
  try {
    const params: PageSysLogOpInput = {
      page: state.operationLogTableParams.page,
      pageSize: state.operationLogTableParams.pageSize,
      controllerName: 'warePlaceModel', // 只查询warePlaceModel模块的操作记录
      ...state.operationLogQueryParams,
    };

    const res = await sysLogOpApi.page(params);
    const result = res.data?.result;
    
    state.operationLogTableData = result?.items || [];
    state.operationLogTableParams.total = result?.total || 0;

    console.log('操作记录数据加载成功:', state.operationLogTableData);
  } catch (error) {
    console.error('加载操作记录数据失败:', error);
    ElMessage.error('加载操作记录数据失败');
  } finally {
    state.operationLogTableLoading = false;
  }
};

// 查询操作记录
const handleOperationLogQuery = () => {
  state.operationLogTableParams.page = 1; // 重置到第一页
  loadOperationLogData();
};

// 重置操作记录查询
const handleOperationLogReset = () => {
  state.operationLogQueryParams = {};
  state.operationLogTableParams.page = 1;
  loadOperationLogData();
};

// 操作记录分页变化
const handleOperationLogPageChange = (page: number) => {
  state.operationLogTableParams.page = page;
  loadOperationLogData();
};

// 操作记录页大小变化
const handleOperationLogSizeChange = (size: number) => {
  state.operationLogTableParams.pageSize = size;
  state.operationLogTableParams.page = 1;
  loadOperationLogData();
};


// 页面加载时
onMounted(async () => {
  await loadBaseData();
  await loadWarehouseDetail();
  // 加载库位数据
  await loadWarePlaceData();
  // 加载操作记录数据
  await loadOperationLogData();
});
</script>

<template>
  <div class="warehouseModel-detail-container">
    <el-card shadow="hover" v-loading="state.loading">
      <!-- 标题栏 -->
      <template #header>
        <div class="card-header">
          <span style="font-size: 18px; font-weight: bold;">仓库仓库: {{ state.warehouseData.wareCode ||
            'CKBH2025102211034557' }}</span>
          <div>
            <el-button type="primary" @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <!-- 仓库信息表单 -->
      <el-form :model="state.warehouseData" label-width="120px" class="warehouse-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="提交人">
              <span class="form-value">{{ state.warehouseData.createUserName || '李敏' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="操作时间">
              <span class="form-value">{{ state.warehouseData.createTime || '2023-07-31 10:19:53' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="更新时间">
              <span class="form-value">{{ state.warehouseData.updateTime || '2023-07-31 10:19:53' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="状态">
              <el-tag v-if="state.warehouseData.wareType !== false" type="success">启用</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="仓库编号">
              <span class="form-value">{{ state.warehouseData.wareCode || 'CKBH048694' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="仓库名称">
              <span class="form-value">{{ state.warehouseData.wareName || '仓库一' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="仓库容量/m³">
              <span class="form-value">{{ state.warehouseData.wareVolume || '500' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="库位数量">
              <span class="form-value" style="color: #409eff; font-weight: bold;">{{ state.locationTableParams.total
                }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="库管部门">
              <span class="form-value">{{ getDepartmentName(state.warehouseData.departmentId) || '部门一' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="仓库主管">
              <span class="form-value">{{ getUserName(state.warehouseData.userId) || '李明明' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="联系电话">
              <span class="form-value">{{ state.warehouseData.contactPhone || '15930411682' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <!-- 空白占位 -->
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="仓库地址">
              <span class="form-value">{{ state.warehouseData.wareAddr || '河南省三门峡市民县文化路956号' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="备注">
              <span class="form-value">{{ state.warehouseData.wareNote || '' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="创建人">
              <span class="form-value">{{ state.warehouseData.createUserName || '赵雨萌' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="创建时间">
              <span class="form-value">{{ state.warehouseData.createTime || '2023-08-01 19:03:01' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="更新人">
              <span class="form-value">{{ state.warehouseData.updateUserName || '张雨' }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="更新时间">
              <span class="form-value">{{ state.warehouseData.updateTime || '2023-08-01 19:03:01' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 库位信息和操作记录标签页 -->
    <el-card shadow="hover" style="margin-top: 10px;">
      <el-tabs v-model="state.activeTab">
        <!-- 库位信息标签页 -->
        <el-tab-pane label="仓位信息" name="locationInfo">
          <!-- 查询条件 -->
          <el-form :model="state.locationQueryParams" inline style="margin-bottom: 10px;">
            <el-form-item label="仓位">
              <el-input v-model="state.locationQueryParams.locationCode" placeholder="请输入仓位名称/编号" clearable
                style="width: 200px;" />
            </el-form-item>
            <el-form-item label="库位状态">
              <el-select v-model="state.locationQueryParams.locationStatus" placeholder="请选择" clearable
                style="width: 150px;">
                <el-option label="全部" value="" />
                <el-option label="启用" value="1" />
                <el-option label="停用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="库位主管">
              <el-input v-model="state.locationQueryParams.locationManager" placeholder="请输入" clearable
                style="width: 150px;" />
            </el-form-item>
            <el-form-item label="">
              <el-button-group>
                <el-button type="primary" icon="ele-Search" @click="handleLocationQuery">查询</el-button>
                <el-button icon="ele-Refresh" style="margin-left: 10px;" @click="handleLocationReset">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-form>

          <!-- 未分配库位提示 -->
          <el-alert v-if="!state.warehouseData.warePlaceId && !state.locationTableLoading" 
            title="该仓库还未分配库位信息" 
            type="info" 
            description="请在仓库编辑页面为该仓库分配库位信息，分配后即可在此查看库位详情。"
            show-icon 
            :closable="false"
            style="margin-bottom: 20px;" />

          <!-- 库位信息表格 -->
          <el-table v-if="state.warehouseData.warePlaceId || state.locationTableLoading" 
            :data="state.locationTableData"
            @selection-change="(val: any[]) => { state.locationSelectData = val; }" style="width: 100%"
            v-loading="state.locationTableLoading" border empty-text="该仓库还未分配库位信息">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="locationCode" label="库位编号" min-width="150" show-overflow-tooltip />
            <el-table-column prop="locationName" label="库位名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="locationVolume" label="库位容量/m³" min-width="120" align="right"
              show-overflow-tooltip />
            <el-table-column prop="locationManager" label="库位主管" min-width="120" show-overflow-tooltip />
            <el-table-column prop="locationStatus" label="库位状态" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.locationStatus" type="success">启用</el-tag>
                <el-tag v-else type="danger">停用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="locationNote" min-width="150" show-overflow-tooltip />
          </el-table>

          <!-- 分页 -->
          <div style="display: flex; justify-content: flex-end; margin-top: 10px;">
            <el-pagination v-model:currentPage="state.locationTableParams.page"
              v-model:page-size="state.locationTableParams.pageSize" :total="state.locationTableParams.total"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" size="small"
              background />
          </div>
        </el-tab-pane>

        <!-- 操作记录标签页 -->
        <el-tab-pane label="操作记录" name="operationRecord">
          <!-- 查询条件 -->
          <el-form :model="state.operationLogQueryParams" inline style="margin-bottom: 10px;">
            <el-form-item label="操作账号">
              <el-input v-model="state.operationLogQueryParams.account" placeholder="请输入操作账号" clearable
                style="width: 200px;" />
            </el-form-item>
            <el-form-item label="操作方法">
              <el-input v-model="state.operationLogQueryParams.actionName" placeholder="请输入操作方法" clearable
                style="width: 200px;" />
            </el-form-item>
            <el-form-item label="IP地址">
              <el-input v-model="state.operationLogQueryParams.remoteIp" placeholder="请输入IP地址" clearable
                style="width: 150px;" />
            </el-form-item>
            <el-form-item label="">
              <el-button-group>
                <el-button type="primary" icon="ele-Search" @click="handleOperationLogQuery">查询</el-button>
                <el-button icon="ele-Refresh" style="margin-left: 10px;" @click="handleOperationLogReset">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-form>

          <!-- 操作记录表格 -->
          <el-table :data="state.operationLogTableData" style="width: 100%"
            v-loading="state.operationLogTableLoading" border empty-text="暂无数据">
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="displayTitle" label="操作名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="actionName" label="操作方法" min-width="120" show-overflow-tooltip />
            <el-table-column prop="account" label="操作账号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="realName" label="操作人员" min-width="120" show-overflow-tooltip />
            <el-table-column prop="remoteIp" label="IP地址" min-width="120" show-overflow-tooltip />
            <el-table-column prop="location" label="操作地点" min-width="150" show-overflow-tooltip />
            <el-table-column prop="browser" label="浏览器" min-width="150" show-overflow-tooltip />
            <el-table-column prop="os" label="操作系统" min-width="120" show-overflow-tooltip />
            <el-table-column prop="elapsed" label="耗时(ms)" width="100" align="right" show-overflow-tooltip />
            <el-table-column prop="status" label="执行状态" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 'Succeeded'" type="success">成功</el-tag>
                <el-tag v-else-if="scope.row.status === 'Failed'" type="danger">失败</el-tag>
                <el-tag v-else type="info">{{ scope.row.status || '未知' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="操作时间" min-width="160" show-overflow-tooltip />
          </el-table>

          <!-- 分页 -->
          <div style="display: flex; justify-content: flex-end; margin-top: 10px;">
            <el-pagination v-model:currentPage="state.operationLogTableParams.page"
              v-model:page-size="state.operationLogTableParams.pageSize" :total="state.operationLogTableParams.total"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" size="small"
              background @current-change="handleOperationLogPageChange" @size-change="handleOperationLogSizeChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

  </div>
</template>

<style scoped lang="scss">
.warehouseModel-detail-container {
  padding: 10px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .warehouse-form {
    .form-value {
      color: #606266;
      font-size: 14px;
    }

    :deep(.el-form-item) {
      margin-bottom: 18px;
    }

    :deep(.el-form-item__label) {
      color: #909399;
      font-weight: normal;
    }
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}
</style>
